package com.zmj.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zmj.demo.pojo.entity.DeptEntity;
import com.zmj.demo.pojo.entity.UserVO;
import com.zmj.demo.service.DeptService;
import com.zmj.framework.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zmj.demo.pojo.entity.UserEntity;
import com.zmj.demo.mapper.IUserMapper;
import com.zmj.demo.service.UserService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mingguang
 * @since 2024-04-01
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<IUserMapper, UserEntity> implements UserService {
    
    @Autowired
    DeptService deptService;
    
    @Override
    public IPage<UserVO> selectPageList(IPage<UserVO> page, Map<String, Object> param) {
        IPage<UserVO> userEntityIPage = baseMapper.selectPageList(page, param);
        List<UserVO> records = userEntityIPage.getRecords();
        if(CollUtil.isEmpty(records)){
            return userEntityIPage;
        }
        Set<Integer> set =new HashSet<>();
        for (UserVO record : records) {
            set.add(record.getDeptId());
            set.add(record.getParentDeptId());
        }
        List<DeptEntity> deptEntities = deptService.listByIds(set);
        if(CollUtil.isEmpty(deptEntities)){
            return userEntityIPage;
        }
        Map<Integer, String> stringMap = deptEntities.stream().collect(Collectors.toMap(DeptEntity::getId, DeptEntity::getName));
        for (UserVO record : records) {
            String deptName = stringMap.get(record.getDeptId());
            record.setDeptName(deptName);
            String parentDeptName = stringMap.get(record.getParentDeptId());
            record.setParentDeptName(parentDeptName);
        }

        return userEntityIPage;
    }
}
